package com.example.tangyee.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tangyee.R;
import com.example.tangyee.bean.HealthVideo;
import com.example.tangyee.utils.GlideApp;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.jzvd.Jzvd;
import cn.jzvd.JzvdStd;

public class HealthVideoPlayerActivity extends AppCompatActivity {

    private static final String TAG = "VideoPlayerActivity";

    private static final String PARAM = "HealthVideo";

    Unbinder mUnbinder;

    @BindView(R.id.health_video_player_back)
    LinearLayout back;
    @BindView(R.id.health_video_player_title)
    TextView topTitle;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.describe)
    TextView describe;
    @BindView(R.id.video_player)
    JzvdStd jzvdStd;

    private HealthVideo mHealthVideo;
    private GetHealthVideoInfo mGetHealthVideoInfo;

    public static void gotoHealthVideoPlayerActivity(Context context, HealthVideo healthVideo) {
        Intent intent = new Intent(context, HealthVideoPlayerActivity.class);
        intent.putExtra(PARAM, healthVideo);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_player);

        mUnbinder = ButterKnife.bind(this);

        // 获取传递过来的参数
        mHealthVideo = getIntent().getParcelableExtra(PARAM);

        title.setText(mHealthVideo.getTitle());

        initViews();
        if (mHealthVideo.getUrl() == null) {
            mGetHealthVideoInfo = new GetHealthVideoInfo(mHealthVideo);
            mGetHealthVideoInfo.execute();
        }
    }

    private void initViews() {
        // 网络视频地址
        String videoUrl = mHealthVideo.getUrl();

        jzvdStd.setUp(videoUrl, mHealthVideo.getTitle(), Jzvd.SCREEN_WINDOW_NORMAL);

        GlideApp.with(this).load(mHealthVideo.getImageUrl()).into(jzvdStd.thumbImageView);

        describe.setText(mHealthVideo.getDesc());
    }

    public class GetHealthVideoInfo extends AsyncTask<Void, Void, HealthVideo> {

        private HealthVideo mVideo;

        GetHealthVideoInfo(HealthVideo healthVideo) {
            this.mVideo = healthVideo;
        }

        @Override
        protected HealthVideo doInBackground(Void... voids) {
            if (isCancelled()) {
                return mVideo;
            }
            try {
                Log.d(TAG, "doInBackground: " + "before");
                Document document = Jsoup.connect(mVideo.getVideoPageUrl()).get();
                Log.d(TAG, "doInBackground: " + "after");
                Element div = document.select("div.mui-content").first();
                Elements spans = div.select("span");
                mVideo.setPromulgator(spans.get(0).text());
                mVideo.setTime(spans.get(1).text());
                mVideo.setDesc(div.select("p.text_dome").first().text());

                String regex = "https?://(\\w*[\\./])*\\w*\\b";

                Matcher m = Pattern.compile(regex).matcher(document.toString());
                if (m.find()) {
                    String r = m.group(0);
                    Log.d(TAG, "doInBackground: " + r);
                    mVideo.setUrl(r);
                }

            } catch (SocketTimeoutException ste) {
                Log.e(TAG, "doInBackground: ", ste);
                return null;
            } catch (IOException e) {
                Log.e(TAG, "doInBackground: ", e);
                return null;
            } catch (IndexOutOfBoundsException ioobe)  {
                Log.e(TAG, "doInBackground: ", ioobe);
                return null;
            }
            return mVideo;
        }

        @Override
        protected void onPostExecute(HealthVideo healthVideo) {
            if (healthVideo == null) {
                Toast.makeText(HealthVideoPlayerActivity.this, "请求超时。", Toast.LENGTH_SHORT).show();
                return;
            }
            mHealthVideo = healthVideo;
            initViews();
        }
    }

    @OnClick(R.id.health_video_player_back)
    public void back(View view) {
        onBackPressed();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mGetHealthVideoInfo != null) {
            mGetHealthVideoInfo.cancel(true);
        }
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

}
